package priv.lhy.ecm.collectorConsumer.nettyServer;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import priv.lhy.common.constants.RedisConstant;
import priv.lhy.ecm.collectorConsumer.datadispose.IDispose;

/**
 * @author: lihy
 * date: 2019/6/18 10:31
 * description:
 */
@Slf4j
@Component
@Qualifier("serverHandler")
@ChannelHandler.Sharable
public class ServerHandler extends SimpleChannelInboundHandler<String> {

    @Value("${netty.delimiter}")
    private String delimiter;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private IDispose dispose;

    /*@Autowired
    private ElectricityServiceImpl electricityService;

    @Autowired
    private WaterMeterServiceImpl waterMeterService;*/

    /*public ServerHandler(@Autowired StringRedisTemplate redisTemplate,
                         @Value("${redis.data.index.company}") int dataIndex) {
        //redisTemplate = RedisUtil.switchDatabase(redisTemplate, dataIndex);
        this.redisTemplate = redisTemplate;
    }*/

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        /**
         * 上传数据格式：
         * token|userCode|uploadType|tableSuffix|jsonData|delimiter
         */
        log.info("接受信息：" + msg);
        String[] message = msg.split("\\|");

        String result;
        if (redisTemplate.opsForSet().isMember(RedisConstant.COLLECTOR_TOKEN, message[0])) {
            //合法数据
            result = dispose.disposeLegalData(message);
            //result = dataDispose(message);
        } else {
            //非法数据
            result = dispose.disposeIllegalData(ctx.channel().localAddress().toString());
            //result = illegalDataDispose(ctx.channel().localAddress().toString());
        }

        ctx.channel().writeAndFlush(result + delimiter);
        ctx.channel().close();

    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
        String ip = ctx.channel().localAddress().toString();
        //IP在黑名单中则禁止连接
        if (redisTemplate.hasKey(RedisConstant.COLLECTOR_IP_BLACK_PREFIX + ":" + ip)) {
            log.info("非法连接。IP:" + ip);
            ctx.channel().close();
        }
    }

    /**
     * 处理合法数据
     *
     * @param message
     * @return
     */
    /*private String dataDispose(String[] message) {
        try {
            switch (UploadType.valueOf(message[2])) {
                case ELECTRICITY:
                    TransferData transferElectricity = JsonUtil.json2Object(message[4],
                            TransferElectricity.class);
                    List<Electricity> electricities = transferElectricity.getList();
                    electricityService.setCompanyCode(message[1]);
                    electricityService.batchAdd(message[3], electricities);
                    break;
                case WATER:
                    TransferData transferWaterMeter = JsonUtil.json2Object(message[4],
                            TransferWatermeter.class);
                    List<Watermeter> waterMeters = transferWaterMeter.getList();
                    waterMeterService.setCompanyCode(message[1]);
                    waterMeterService.batchAdd(message[3], waterMeters);
                default:
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "error";
        }
        return "ok";
    }*/


    /**
     * 处理非法数据
     *
     * @param ip
     * @return
     */
    /*private String illegalDataDispose(String ip) {
        int errorCount = 0;
        if (redisTemplate.hasKey(RedisConstant.COLLECTOR_IP_ERROR_PREFIX + ":" + ip)) {
            errorCount = Integer.valueOf(redisTemplate.opsForValue().get(RedisConstant
                    .COLLECTOR_IP_ERROR_PREFIX + ":" + ip));
        }
        errorCount++;
        if (errorCount >= RedisConstant.COLLECTOR_IP_ERROR_TIME) {
            //达到重试次数，加入黑名单
            redisTemplate.opsForValue().set(RedisConstant
                    .COLLECTOR_IP_BLACK_PREFIX + ":" + ip, "1", RedisConstant
                    .COLLECTOR_BLACK_EXPIRE, TimeUnit.MINUTES);
        } else {
            //未达到重试次数，自增一
            redisTemplate.boundValueOps(RedisConstant.COLLECTOR_IP_ERROR_PREFIX + ":" + ip).increment(1);
            redisTemplate.expire(RedisConstant.COLLECTOR_IP_ERROR_PREFIX + ":" + ip,
                    RedisConstant.COLLECTOR_BLACK_EXPIRE, TimeUnit.MINUTES);
        }
        return "非法数据，还可重试" + (RedisConstant.COLLECTOR_IP_ERROR_TIME - errorCount) + "次";
    }*/

}
